<!--数据字典管理-->
<template>
    <div>
        <a-card>
            <p slot="title">
                检索条件
            </p>
            <div class="formSearch">
                <a-form ref="sysRoleDTO" :label-width="80" layout="inline"
                        @keydown.native.enter.prevent="handleSubmit">
                    <a-form-item label="关键字：" prop="searchKey">
                        <a-input v-model="searchKey" placeholder="请输入角色名称搜索"
                                 @keyup="formatEnterContent(searchKey)"
                                 @blur="formatEnterContent(searchKey)" style="width: 220px">
                            <a-icon slot="prefix" type="user" class="displayPre" />
                            <a-icon v-if="searchKey" slot="suffix" type="close-circle" @click="emitEmpty(searchKey)" />
                        </a-input>
                    </a-form-item>
                    <a-form-item label="组织机构：" prop="orgId" v-if="permission.sysOrg">
                        <a-tree-select
                                style="width: 220px" v-model="orgId"
                                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                                :treeData="getOrgTree" placeholder="全部">
                            <span style="color: #08c" slot="title" slot-scope="{key, title}">{{title}}</span>
                        </a-tree-select>
                    </a-form-item>
                    <a-button type="primary" @click="handleSubmit"
                              v-if="hasPermission('sysrole:findSysRoles')">查询
                    </a-button>
                    <a-button style="margin-left: 8px" @click="reStore">重置</a-button>
                </a-form>
            </div>
        </a-card>
        <div style="height: 10px"></div>
        <div class="commonStyle nyContent">
            <div class="table-operator">
                <a-button type="primary"  @click="addRole" v-if="hasPermission('sysrole:addSysRole')">新增</a-button>
                <a-button type="danger"  @click="delRole" v-if="hasPermission('sysrole:delSysRoles')">批量删除</a-button>
            </div>
            <a-table :columns="columns" :dataSource="getSysRoleDTOs" :rowKey="record => record.id"
                     :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                     :pagination="false">
                <span slot="index" slot-scope="text, record, index">
                    {{ (page.currentPage - 1) * page.pageSize + index + 1 }}
                </span>
                <span slot="limited" slot-scope="text">
                    {{ text === '1' ? '是' : '否' }}
                </span>
                <span slot="type" slot-scope="text">
                    {{text | filterWord(roleTypeList)}}
                </span>
                <span slot="validStatus" slot-scope="text"  :style="text !== '1'?'color:#ddd':'color:green'">
                    {{ text === '1' ? '启用' : '停用' }}
                </span>
                <span slot="description" slot-scope="text">
                        <ellipsis :length="12" tooltip :fullString="text"></ellipsis>
                </span>
                <span slot="operation" slot-scope="text" class="table-operation">
                         <a @click="editRoleAuth(text)" v-if="permission.editButtonShow ">
                            编辑</a>
                                <a @click="enableRoleAuth(text)"
                                   v-if="permission.showDisableRoleBtn && text.validStatus === '0' ">
                            启用</a><a @click="disableRoleAuth(text)" class="adel"
                                     v-if="permission.showDisableRoleBtn && text.validStatus === '1' ">
                            停用</a><a @click="roleAuthShow(text)" v-if="permission.showRoleAuthBtn">
                            用户权限管理</a>
                </span>
            </a-table>
            <Page :totalCount="pageVal.total" :currentPage="pageVal.currentPage" ref="page"
                  :pageSize="pageVal.pageSize" @changePage="changePage" @changePageSize="changePageSize" />
        </div>
        <add-edit ref="addEdit"
                  :title="title"
                  :orgTree="getOrgTree"
                  :roleTypeList="roleTypeList"
                  :permission="permission"
                  :sysRoleDTO="sysRoleDTO" @init="init" />
    </div>
</template>

<script>
    import addEdit from './addEdit.vue'
    import { mapState } from 'vuex'
    import Page from 'module/pagination'
    import Util from '@/libs/util';
    import ellipsis from 'module/ellipsis'
    export default {
        name: 'sys_role',
        components: {
            addEdit,
            Page,
            ellipsis
        },
        data () {
            return {
                title: true,
                permission: {
                    editButtonShow: false,
                    showRoleAuthBtn: false,
                    showEnableRoleBtn: false,
                    showDisableRoleBtn: false,
                    sysOrg: false
                },
                searchKey: '',
                orgId: '',
                orgName: '',
                selectedNode: {id: '', name: ''},
                array: [ 10, 20, 30, 40 ],
                /*选中的记录*/
                selectedRowKeys: [],
                sysRoleDTO: {
                    id: '',
                    name: '',
                    orgId: '',
                    orgName: '',
                    limited: '0',
                    validStatus: '',
                    description: '',
                    createTime: ''
                },
                page: {
                    currentPage: 1,
                    pageSize: 10
                },
                columns: [
                    {title: '序号', key: 'index', width: '7%', align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: '角色名称', dataIndex: 'name', key: 'name'},
                    {title: '机构名称', dataIndex: 'orgName', key: 'orgName'},
                   /* {
                        title: '角色类型',
                        dataIndex: 'type',
                        key: 'type',
                        scopedSlots: {customRender: 'type'}
                    },*/
                    /*{title: '受限角色', dataIndex: 'limited', key: 'limited', scopedSlots: {customRender: 'limited'}},*/
                    {
                        title: '有效状态',
                        dataIndex: 'validStatus',
                        key: 'validStatus',
                        scopedSlots: {customRender: 'validStatus'}
                    },
                    {
                        title: '创建时间',
                        dataIndex: 'createTime',
                        key: 'createTime'
                    },
                    {title: '操作', key: 'operation', width: '16%', scopedSlots: {customRender: 'operation'}}
                ],
            }
        },
        computed: {
            getSysRoleDTOs () {
                return this.$store.state.sysRole.sysRoleDTOs
            },
            ...mapState ({
                pageVal: state => state.sysRole.page,
                roleTypeList: state => state.common.roleTypeList,
            }),
            getOrgTree () {
                return this.$store.state.sysOrg.sysOrgTree
            }
        },
        filters: {
            filterWord(value, list) {
                for (let i=0; i<list.length; i++) {
                    if (value === list[i].value) {
                        return list[i].label
                    }
                }
            },
        },
        methods: {
            emitEmpty () {
                this.searchKey = ''
                this.init ()
            },
            reStore(){
                this.searchKey = ''
                this.orgId = undefined
                this.orgName = ''
                this.page.currentPage = 1
                this.init();
            },
            /*
             * 过滤输入框输入的特殊字符
             * */
            formatEnterContent ( value ) {
                let a = Util.clearSpecialChart(value);
                this.searchKey = a
            },
            /**
             * Function    : editRoleAuth
             * Description : 修改系统用户信息
             * Input       : userName 用户名
             * Return      : none
             */
            editRoleAuth ( rowData ) {
                this.title = false
                this.$refs.addEdit.showEdit (rowData)
            },
            /**
             * Function    : enableRoleAuth
             * Description : 用户启用
             * Input       : userName 用户名
             * Return      : none
             */
            enableRoleAuth ( text ) {
                this.$confirm ({
                    title: `确定启用${text.name}用户吗?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.$store.dispatch ('enableSysRoleAct', {ids: text.id}).then (response => {
                            if (response.code === 0) {
                                this.$message.success (response.message)
                                this.init ()
                            } else {
                                this.$message.error (response.message)
                            }
                        })
                    }
                })
            },
            /**
             * Function    : disableRoleAuth
             * Description : 用户启用
             * Input       : userName 用户名
             * Return      : none
             */
            disableRoleAuth ( text ) {
                this.$confirm ({
                    title: `确定禁用${text.name}用户吗?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.$store.dispatch ('disableSysRoleAct', {ids: text.id}).then (response => {
                            if (response.code === 0) {
                                this.$message.success (response.message)
                                this.init ()
                            } else {
                                this.$message.error (response.message)
                            }
                        })
                    }
                })
            },
            /**
             * Function    : roleAuthShow
             * Description : 用户权限管理
             * Input       : userName 用户名
             * Return      : none
             */
            roleAuthShow ( text ) {
                let query = {
                    id: text.id,
                    name: text.name,
                    orgName: text.orgName
                }
                this.$router.push ({
                    name: 'roleAuth',
                    query: query
                })
            },
            /**
             * Function    : init
             * Description : 初始化列表
             * Input       : none
             * Return      : none
             */
            init () {
                let para = Object.assign ({},
                  {searchKey: this.searchKey.trim ()},
                  {orgId: this.orgId, orgName: this.orgName}, this.page)
                this.selectedRowKeys = []
                this.$store.dispatch ('getSysRolesAct', para)
                this.$store.commit ('setRoleQueryPrams', para)
            },

            /**
             * Function    : addRole
             * Description : 新增数据字典
             * Input       : none
             * Return      : none
             */
            addRole () {
                this.clearSysRoleDTO ()
                this.title = true
                this.$refs.addEdit.showModal ()
            },

            /**
             * Function    : checkCol
             * Description : 选择框事件
             * Input       : sel
             * Return      : none
             */
            checkCol ( sel ) {
                let check = []
                sel.forEach (( item, index ) => {
                    check.push (item)
                })
                this.checkData = check
            },
            /**
             * Function    : onSelectChange
             * Description : 选择当前行id
             * Input       : none
             * Return      : none
             */
            onSelectChange (selectedRowKeys) {
                this.selectedRowKeys = selectedRowKeys
            },
            /**
             * Function    : delRole
             * Description : 批量删除角色
             * Input       : none
             * Return      : none
             */
            delRole () {
                var ids = ''
                var cArry = []
                this.selectedRowKeys.forEach (( item, index ) => {
                    if (index === 0) {
                        ids = item.id
                    } else {
                        ids += ',' + item.id
                    }
                    cArry.push (index)
                })
                if (this.selectedRowKeys.length <= 0) {
                    cArry =[];
                    this.$message.info ('请至少选择一条系统角色记录',3)
                    return
                }
                ids = this.selectedRowKeys.join(',')
                this.$confirm ({
                    title: '确认删除选中的系统角色吗？',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        let _this = this
                        this.$store.dispatch ('batchDelSysRolesAct', {ids: ids}).then (response => {
                            if (response.code === 0) {
                                if (cArry.length === _this.getSysRoleDTOs.length && _this.page.currentPage > 1) {
                                    _this.page.currentPage = _this.page.currentPage - 1
                                }
                                _this.init ()
                                this.$message.success (response.message)
                            } else {
                                this.$message.error (response.message)
                            }
                            ids = ''
                            cArry = []
                        })
                    },
                    onCancel: () => {
                        ids = ''
                        cArry = []
                    }
                })
            },

            /**
             * Function    : changePage
             * Description : 切换页码
             * Input       : val
             * Return      : none
             */
            changePage ( val ) {
                this.page.currentPage = val
                this.init ()
            },

            /**
             * Function    : changePageSize
             * Description : 切换每页条数
             * Input       : vm
             * Return      : none
             */
            changePageSize ( vm ) {
                this.page.pageSize = vm
                this.page.currentPage = 1
                this.init ()
            },

            /**
             * Function    : handleSubmit
             * Description : 查询按钮
             * Input       : none
             * Return      : none
             */
            handleSubmit () {
                this.page.currentPage = 1
                this.init ()
            },

            /**
             * Function    : clearSysRoleDTO
             * Description : 初始化系统角色配置
             * Input       : none
             * Return      : none
             */
            clearSysRoleDTO () {
                this.sysRoleDTO = {
                    id: '',
                    name: '',
                    orgId: '',
                    orgName: '',
                    limited: '0',
                    validStatus: '',
                    description: '',
                    createTime: ''
                }
            },
            selectNodeId ( val ) {
                this.orgId = val.id
                this.orgName = val.name
            },

            /**
             * Function    : initPermission
             * Description : 初始化权限码
             * Input       : none
             * Return      : none
             */
            initPermission () {
                this.permission = {
                    editButtonShow: this.hasPermission ('sysrole:updSysRole'),
                    showRoleAuthBtn: this.hasPermission ('sysRole:roleAuth'),
                    showEnableRoleBtn: this.hasPermission ('sysrole:enableSysRoles'),
                    showDisableRoleBtn: this.hasPermission ('sysrole:disableSysRoles'),
                    sysOrg: this.hasPermission ('system:sysOrg')
                }
            }
        },
        created () {
            this.initPermission ()
            //this.$store.dispatch ('loadSysDictsAct',{code:this.$dicts.sortCode.role_type,list:'roleTypeList'})
            let sliceLen = 8
            if (!this.permission.sysOrg) {
                this.columns = this.columns.filter (( item ) => {
                    if (item.key !== 'orgName') {
                        return item
                    }
                })
                sliceLen = sliceLen - 1
            }

            if (!( this.permission.editButtonShow || this.permission.showRoleAuthBtn
              || this.permission.showEnableRoleBtn || this.permission.showDisableRoleBtn )) {
                this.columns = this.columns.splice (0, sliceLen)
                this.columns.shift ()
            }
            this.searchKey = this.$route.query.searchKey === undefined ? '' : this.$route.query.searchKey
            this.orgId = this.$route.query.orgId === undefined ? '' : this.$route.query.orgId
            this.orgName = this.$route.query.orgName === undefined ? '' : this.$route.query.orgName
            this.page.currentPage = this.$route.query.currentPage === undefined ? 1 : this.$route.query.currentPage
            this.page.pageSize = this.$route.query.pageSize === undefined ? 10 : this.$route.query.pageSize
            this.$store.dispatch ('loadSysOrgTreeAct')
            this.init ()
        },
        mounted () {
            this.selectedNode = {
                id: this.orgId,
                name: this.orgName
            }
        }
    }
</script>
